<template>
  <div id="editeds" class="wrap">
    <div class="title">预约门店</div>
    <div class="wrapper">
      <div class="wrapperBody">
        <div class="father">
          <div class="left">
            <div class="list firlist">
              <span class="txt" style="margin-left: 14px;">客户报名费用：</span>
              <input class="input" placeholder v-model="form.activityPrice" @input="setPr()">
              <span class="moneys">元</span>
              <span class="titlesned">免费活动可不填写或填写0元。</span>
            </div>
            <div class="list firlist">
              <span class="txt" style="margin-left: 14px;">
                <img class="red" src="../../images/main/red.png" alt>适用年龄：
              </span>
              <input
                style="width:150px;"
                class="input"
                type="tel"
                v-model="form.ageks"
                @input="ageStartInput"
              >
              <span>-</span>
              <input
                style="width:150px;margin-left:0;"
                class="input"
                type="tel"
                v-model="form.agejs"
                @input="ageEndInput"
              >
              <span class="moneys">岁</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <span
                style="font-size:14px;color:#085dab;font-weight:700"
              >例如：2-3</span>
              <p class="nullRed" v-if="a">请填写年龄</p>
            </div>
            <div class="list firlist twolist" style="overflow: hidden;">
              <span class="txt" style="float:left">
                <img class="red" src="../../images/main/red.png" alt>
                活动海报：
              </span>
              <div
                :style="{
                  width: '300px',
                  height: '300px',
                  overflow: 'hidden',
                  float: 'left',
                  marginLeft: '50px'
                }"
              >
                <img
                  class="imged"
                  :src="form.activityImg || require('../../images/main/upimg.png')"
                  ref="preview"
                  alt
                >
              </div>

              <!-- <span class="titlerf">请上传海报活动</span> -->
              <div class="rightList" style="float:left">
                <p>温馨提示：</p>
                <p style="margin-top: 25px;">建议上传尺寸为960*675，大小不超过4M,jpg或png格式</p>
                <el-upload
                  :http-request="httpRequest"
                  :multiple="false"
                  class="upload-demo"
                  accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .GIF"
                  :action="$store.state.url+ '/service/upload'"
                >
                  <el-button
                    size="small"
                    type="primary"
                    class="btn"
                  >{{form.activityImg ? '重新上传' : '点击上传'}}</el-button>
                </el-upload>
              </div>
            </div>
            <div style="clear:both;"></div>
            <p class="nullRed" v-if="b" style="margin-top:20px;">请上传海报</p>
          </div>
          <!-- <div class="right">

          </div>-->
        </div>
      </div>
      <div style="padding-top: 74px;">
        <div class="execled">
          <quill-editor
            class="needsclick"
            v-model="content"
            ref="myQuillEditor"
            :options="editorOption"
            style="user-select:text"
            @blur="onedit($event)"
            @ready="onedit($event)"
            @focus="onedit($event)"
            @change="onedit($event)"
          ></quill-editor>
          <div class="nullRed" v-if="c" style="margin:10px 0;">请先输入活动详情</div>
        </div>

        <!-- <div class="detailsed">请先输入活动详情</div> -->
      </div>
      <ul class="ends">
        <li>
          <div class="btn" @click="read()">
            <span>预览</span>
          </div>
        </li>
        <li>
          <div class="btn" @click="prev()">
            <span>上一步</span>
          </div>
        </li>
        <li>
          <div class="btn" @click="saveAc()">
            <span>发布活动</span>
          </div>
        </li>
      </ul>
    </div>
    <el-dialog title="预览" :visible.sync="dialogTableVisible">
      <y-l
        :content="{
          details: form.activityDetails,
          participateMin: form.participateMin,
          activityTitle: form.activityTitle,
          activityAddress: form.activityAddress,
          activityPrice: form.activityPrice,
          ageks: form.ageks,
          agejs: form.agejs,
          startTime: form.startTime,
          time: form.time
        }"
        v-if="dialogTableVisible"
      ></y-l>
    </el-dialog>
  </div>
</template>
<script>
import { quillRedefine } from "vue-quill-editor-upload";
import { quillEditor } from "vue-quill-editor";
import qs from "qs";
import yL from "./read.vue";
import Global from "./../tool/Global.vue";
import { compress } from "./../tool/utils.js";
export default {
  components: {
    // 引入组件
    quillEditor,
    quillRedefine,
    yL
  },
  data: function() {
    return {
      a: false,
      b: false,
      c: false,
      content: "",
      editorOption: {},
      childfrom: {},
      dialogTableVisible: false,
      isConfirm: true,
      params: this.decodeJson(this.$route.query.p)
    };
  },
  computed: {
    editor() {
      this.$nextTick(function() {
        this.$refs.myQuillEditor.quill.enable(true);
        this.$refs.myQuillEditor.quill.blur();
        return this.$refs.myQuillEditor.quillEditor;
      });
    }
  },
  props: ["form"],
  methods: {
    /**
     * 处理图片
     */
    httpRequest(options) {
      var that = this;
      // 获取文件对象
      let file = options.file;
      //判断图片类型
      if (
        file.type == "image/jpeg" ||
        file.type == "image/png" ||
        file.type == "image/JPG"
      ) {
        var isJPG = true;
      } else {
        isJPG = false;
      }
      // 判断图片大小
      const isLt8M = file.size / 1024 / 1024 < 8;
      if (!isJPG) {
        this.$message.error("上传产品图片只能是 JPG/PNG/JPEG 格式!");
      }
      if (!isLt8M) {
        this.$message.error("上传产品图片大小不能超过 8MB!");
      }
      // 创建一个HTML5的FileReader对象
      var reader = new FileReader();
      //创建一个img对象
      var img = new Image();
      let filename = options.filename;
      if (file) {
        reader.readAsDataURL(file);
      }
      if (isJPG && isLt8M) {
        reader.onload = e => {
          let base64Str = reader.result.split(",")[1];
          img.src = e.target.result;
          // base64地址图片加载完毕后执行
          img.onload = function() {
            // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
            var canvas = document.createElement("canvas");
            var context = canvas.getContext("2d");
            // 图片原始尺寸
            var originWidth = this.width;
            var originHeight = this.height;
            // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
            var maxWidth = 300,
              maxHeight = 300;
            // 目标尺寸
            var targetWidth = originWidth,
              targetHeight = originHeight;
            // 图片尺寸超过最大尺寸的限制
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更改宽度，按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(
                  maxWidth * (originHeight / originWidth)
                );
              } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(
                  maxHeight * (originWidth / originHeight)
                );
              }
            }
            //对图片进行缩放
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            // 清除画布
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片压缩
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            /*第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
            //压缩后的base64文件
            var newUrl = canvas.toDataURL("image/jpeg", 0.92);
            var formData = new FormData();
            formData.append(
              "file",
              that.convertBase64UrlToBlob(newUrl, "gionlee.png")
            );
            that.axios
              .post(that.$store.state.url + "/service/upload", formData)
              .then(res => {
                if (res.data.code == 0) {
                   that.$set(that.form,"activityImg", res.data.data.src)
                } else {
                  that.$alert(res.data.msg);
                }
              });
          };
        };
      }
    },
    /**
     * 转换图片格式
     */
    convertBase64UrlToBlob(urlData, filename) {
      var arr = urlData.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 图片加载完修改尺寸
    fixPreviewStyle(src) {
      let img = new Image();
      img.src = src;
      img.onload = () => {
        let el = this.$refs.preview;
        let w = img.width && img.width;
        let h = img.height && img.height;
        if (w == h) {
          el.style.width = "300px";
        } else if (w < h) {
          el.style.height = "300px";
          el.style.width = (300 / h) * w + "px";
          el.style.marginLeft = (300 - (300 / h) * w) / 2 + "px";
        } else if (h < w) {
          el.style.width = "300px";
          el.style.height = (300 / w) * h + "px";
          el.style.marginTop = (300 - (300 / w) * h) / 2 + "px";
        }
      };
    },
    onedit() {
      console.log("111");
    },
    ageStartInput() {
      this.form.ageks = this.form.ageks.replace(/[^0-9]/gi, "");
      if (this.form.ageks > 100) {
        this.form.ageks = 100;
      } else if (this.form.ageks < 1 && this.form.ageks != "") {
        this.form.ageks = 1;
      }
    },
    ageEndInput() {
      this.form.agejs = this.form.agejs.replace(/[^0-9]/gi, "");
      if (this.form.agejs > 100) {
        this.form.agejs = 100;
      } else if (this.form.agejs < 1 && this.form.agejs) {
        this.form.agejs = 1;
      }
    },
    /**
     * 设置年龄
     */
    szNl: function() {
      this.form.age = this.form.age.replace(/[^0-9]-[^0-9]/gi, "");
    },
    /**
     * 设置费用
     */
    setPr: function() {
      this.form.activityPrice = this.form.activityPrice
        .replace(/^0*(0\.|[1-9])/, "$1")
        .replace(/[^\d.]/g, "")
        .replace(/\.{2,}/g, ".")
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".")
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");

      if (this.form.activityPrice < 0) {
        this.form.activityPrice = 0;
      }
      if (this.form.activityPrice > 99999) {
        this.form.activityPrice = 99999;
      }
    },
    uploadsu(response, file, item) {
      // this.form.activityImg = response.data.src;
      this.$set(this.form, "activityImg", response.data.src);
      this.fixPreviewStyle(response.data.src);
      this.b = false;
    },
    elUploadBefore(file) {
      const isImg = file.type.search("image/") == -1;
      const isLt8M = file.size / 1024 / 1024 < 4;

      if (isImg) {
        this.$message.error("请上传图片类型!");
      }
      if (!isLt8M) {
        this.$message.error("图片大小不能超过 8MB!");
      }
      compress(file.raw, function(val) {
      });
      return !isImg && isLt8M;
    },
    prev: function() {
      this.$emit("go-bespeak", this.childfrom);
    },
    /**
     * 预览
     */
    read: function() {
      sessionStorage.setItem("acInfo", JSON.stringify(this.form));
      this.dialogTableVisible = true;
    },
    /**
     * 保存活动
     */
    saveAc: function() {
      let that = this;

      if (that.form.ageks && that.form.agejs) {
        if (Number(that.form.ageks) > Number(that.form.agejs)) {
          that.$alert("请输入正确的年龄范围!");
        } else {
          that.form.age = that.form.ageks + "-" + that.form.agejs;
        }
      } else {
        that.a = true;
      }

      // that.form.activityImg = that.upImg;
      that.form.serviceId = this.$store.state.userId;
      if (!that.form.activityImg) {
        that.b = true;
      }

      if (!that.form.activityDetails) {
        that.c = true;
        return false;
      }

      if (
        !that.form.age ||
        !that.form.activityImg ||
        !that.form.activityDetails
      ) {
        return false;
      }

      let actCotent = that.form.activityDetails;
      actCotent = actCotent.replace(/\s/gim, "");
      actCotent = actCotent.replace("<p></p>", "");

      if (actCotent == "") {
        this.$alert("请输入活动详情");
        return false;
      }
      for (let key in that.form) {
        if (key == "releaseTime" || key == "endTime" || key == "activityTime") {
          delete that.form[key];
        }
      }
      let data = that.form;
      delete data.closingTime;
      if (this.params.again) {
        delete data.id;
      }
      if (!that.isConfirm) {
        return false;
      } else {
        that.isConfirm = false;
      }
      that
        .axios({
          method: "post",
          // url: "activity/addActivity",
          url: "activity/updateActivity",
          data: qs.stringify(that.form)
        })
        .then(res => {
          that.isConfirm = true;
          if (res.data.code == 0) {
            that.$router.push({
              path: "/main/success",
              query: {
                p: this.encodeJson({
                  activityId: this.params.activityId || res.data.data
                })
              }
            });
          } else {
            that.$alert(res.data.msg);
          }
        });
    }
  },
  mounted() {
    let that = this;
    if (that.form.age) {
      that.form.ageks = that.form.age.split("-")[0];
      that.form.agejs = that.form.age.split("-")[1];
    }
  },
  watch: {
    content: function(res) {
      this.form.activityDetails = res;
      if (res) {
        this.c = false;
      }
    },
    form: function(res) {
      let that = this;
      this.childfrom = res;
      if (that.form.activityPrice < 0) {
        that.form.activityPrice = 0;
      }
      if (that.form.age) {
        that.form.ageks = that.form.age.split("-")[0];
        that.form.agejs = that.form.age.split("-")[1];
      }
      that.content = that.form.activityDetails;
    }
  },
  created() {
    let that = this;
    if (that.form.age) {
      that.form.ageks = that.form.age.split("-")[0];
      that.form.agejs = that.form.age.split("-")[1];
    }
    that.editorOption = quillRedefine({
      // 图片上传的设置
      uploadConfig: {
        // action: "http://114.116.100.38/service/api/service/upload",
         action: "https://sharespace.cloudjoyclub.com//service/api/service/upload", // 必填参数 图片上传地址
        // 必选参数  res是一个函数，函数接收的response为上传成功时服务器返回的数据
        // 你必须把返回的数据中所包含的图片地址 return 回去
        res: res => {
          return res.data.src;
        },
        methods: "POST", // 可选参数 图片上传方式  默认为post
        token: sessionStorage.token, // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
        name: "file", // 可选参数 文件的参数名 默认为img
        size: 1024 * 4, // 可选参数   图片限制大小，单位为Kb, 1M = 1024Kb
        accept: "image/png, image/gif, image/jpeg, image/bmp, image/x-icon", // 可选参数 可上传的图片格式
        // start: function (){}
        start: () => {}, // 可选参数 接收一个函数 开始上传数据时会触发
        end: () => {}, // 可选参数 接收一个函数 上传数据完成（成功或者失败）时会触发
        success: () => {}, // 可选参数 接收一个函数 上传数据成功时会触发
        error: () => {} // 可选参数 接收一个函数 上传数据中断时会触发
      },
      // 以下所有设置都和vue-quill-editor本身所对应
      placeholder: "", // 可选参数 富文本框内的提示语
      handlers: {
        image: function(value) {
          if (value) {
            document.querySelector("#quill-upload input").click();
          } else {
            this.quill.format("image", false);
          }
        }
      }
    });
  }
};
</script>
<style>
/* 上传列表干掉了 */
.el-upload-list {
  display: none;
}

.quill-editor {
  height: 440px;
}
.quill-editor .ql-container {
  height: 370px;
}
</style>

<style scoped>
.nullRed {
  color: red;
  font-size: 12px;
  margin-left: 200px;
}
.wrap {
  width: 90%;
  margin: 40px auto;
}
#editeds {
  /* padding-left: 136px; */
  /* width: 100%; */
  width: 90%;
  margin: 40px auto;
}
#editeds .head {
  /* width: 1200px; */
  height: 60px;
  overflow: hidden;
  position: relative;
  margin-left: 258px;
  margin-top: 10px;
  margin-bottom: 98px;
}
#editeds .bespeak {
  width: 580px;
  height: 60px;
  left: 0;
  background-size: cover;
  position: absolute;
  font-size: 18px;
  color: #ffffff;
  text-align: center;
  line-height: 60px;
  font-weight: bold;
}
#editeds .edit img {
  position: absolute;
  z-index: -999;
  right: 0;
}
#editeds .edit {
  cursor: pointer;
  width: 620px;
  height: 60px;
  position: absolute;
  right: 0;
  font-size: 18px;
  color: #085dab;
  text-align: center;
  line-height: 60px;
  font-weight: bold;
}
#editeds .bespeak img {
  position: absolute;
  z-index: -999;
  left: 0;
}
#editeds .title {
  height: 33px;
  line-height: 33px;
  font-size: 24px;
  font-family: PingFangSC-Medium;
  font-weight: bold;
  margin-top: 99px;
}
#editeds .wrapper {
  border-top: 1px solid #9e9f9f;
  /* width: 1641px; */
  /* width: 90%; */
  margin: 24px auto 0;
  /* margin-top: 24px; */
}
#editeds .wrapperBody {
  margin-top: 64px;
  /* padding-left: 85px; */
  /* height: 425px; */
}
#editeds .list {
  /* height: 40px; */
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #000000;
  line-height: 40px;
  margin-top: 49px;
}
#editeds .lastlist {
  height: 182px;
}
#editeds .twolist {
  margin-top: 78px;
  position: relative;
}
#editeds .red {
  width: 10px;
  height: 10px;
}
#editeds .txt {
  width: 145px;
  display: inline-block;
  text-align: left;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  font-weight: bold;
  color: #000000;
}
#editeds .execled {
  /* width: 1025px; */
  height: 481px;
  margin-left: 210px;
}
#editeds .firlist input {
  width: 317px;
  height: 40px;
}
#editeds .input {
  background: #ffffff;
  box-shadow: inset 0 1px 3px 0 rgba(0, 0, 0, 0.5);
  margin-left: 35px;
  padding-left: 10px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #888888;
  box-sizing: border-box;
  text-align: center;
}
#editeds .imged {
  background: #f6f6f6;
  width: 300px;
  height: 300px;
  /* width: 360px;
  height: 225px;*/
  /*margin-left: 35px;*/
  /* position: absolute;
  top: 0px;
  left: 165px; */
  /*float: left;*/
  /*margin-left: 50px;*/
}
#editeds .moneys {
  background: #085dab;
  border: 1px solid #979797;
  width: 38px;
  height: 38px;
  color: white;
  display: inline-block;
  margin-left: -9px;
  text-align: center;
}
#editeds .titlesned {
  margin-left: 37px;
  font-family: PingFangSC-Medium;
  font-size: 14px;
  color: #085dab;
  letter-spacing: 0.01px;
  text-align: left;
  font-weight: bold;
}
#editeds .title img {
  width: 28px;
  height: 26px;
  float: left;
  padding-top: 5px;
  margin-right: 10px;
}
#editeds .titlerf {
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #f70000;
  letter-spacing: 0;
  text-align: left;
  position: absolute;
  top: 228px;
  left: 198px;
  font-weight: bold;
}
#editeds .left {
  /* float: left; */
}
#editeds .right {
  /* float: right; */
}
#editeds .father {
  /* height: 226px; */
  /* width: 1198px; */
}
#editeds .rightList {
  width: 472px;
  height: 179px;
  margin-left: 40px;
}
#editeds .rightList p {
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #888888;
  letter-spacing: 0.03px;
  text-align: left;
  font-weight: bold;
}
#editeds .btn {
  background: #085dab;
  width: 255px;
  height: 55px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #ffffff;
  letter-spacing: 0.03px;
  text-align: center;
  line-height: 55px !important;
  margin-top: 30px;
  cursor: pointer;
  padding: 0px;
}
#editeds .detailsed {
  margin-top: 30px;
  font-family: PingFangSC-Medium;
  font-size: 14px;
  color: #fa0101;
  letter-spacing: 0.01px;
  text-align: left;
  margin-left: 213px;
  font-weight: bold;
}
#editeds .ends {
  /* margin-left: 361px; */
  /* width: 1200px; */
  width: 900px;
  height: 40px;
  padding-bottom: 109px;
  margin: 0 auto;
}
#editeds .ends li {
  /* margin-left: 60px; */
  padding: 0 25px;
  width: 250px;
  float: left;
}
</style>
